// @ts-ignore
import fs from 'fs';
import nodemailer from 'nodemailer';

// Read test results
const report = JSON.parse(fs.readFileSync('results.json', 'utf-8'));

// 获取当前日期
const today = new Date();
const dateStr = today.toISOString().slice(0, 10);

// 统计用例
let total = 0, passed = 0, failed = 0;
let failRows = '', allRows = '';

// UTC时间转北京时间字符串
function formatToBeijingTime(utcStr: string): string {
    if (!utcStr) return '';
    const date = new Date(utcStr);
    // 取UTC时间分量，加8小时
    const yyyy = date.getUTCFullYear();
    const MM = String(date.getUTCMonth() + 1).padStart(2, '0');
    const dd = String(date.getUTCDate()).padStart(2, '0');
    let hh = date.getUTCHours() + 8;
    let day = dd;
    // 跨天处理
    if (hh >= 24) {
        hh -= 24;
        // 简单处理：直接加一天（不考虑月末/闰年，实际可用 Date 对象处理）
        const tempDate = new Date(Date.UTC(yyyy, date.getUTCMonth(), date.getUTCDate() + 1));
        day = String(tempDate.getUTCDate()).padStart(2, '0');
        // 也可重新取年月日
        return `${tempDate.getUTCFullYear()}-${String(tempDate.getUTCMonth() + 1).padStart(2, '0')}-${day} ${String(hh).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}:${String(date.getUTCSeconds()).padStart(2, '0')}`;
    }
    return `${yyyy}-${MM}-${dd} ${String(hh).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}:${String(date.getUTCSeconds()).padStart(2, '0')}`;
}


for (const suite of report.suites) {
    for (const spec of suite.specs) {
        for (const test of spec.tests) {
            total++;
            const result = test.results[0];
            const actual = result?.status || '';
            const duration = result?.duration || '';
            // 转为北京时间
            const startTime = formatToBeijingTime(result?.startTime);
            let errorMsg = '';
            let rowStyle = '';
            if (actual === 'passed') passed++;
            else if (actual === 'failed') {
                failed++;
                rowStyle = "background:#ffecec; color:#d8000c;";
            }
            if (result?.error?.message) {
                errorMsg = `<span style='color:red;'>${result.error.message.replace(/\n/g, '<br>')}</span>`;
            }
            const row = `<tr style='${rowStyle}'>
        <td>${spec.title}</td>
        <td>${startTime}</td>
        <td>${actual}</td>
        <td>${duration}</td>
        <td>${errorMsg}</td>
      </tr>`;
            allRows += row;
            if (actual === 'failed') failRows += row;
        }
    }
}

const summaryHtml = `<div style='margin-bottom:12px;'>
  <b>测试日期：</b>${dateStr}<br>
  <b>总用例数：</b>${total} &nbsp; <b>通过：</b><span style='color:green;'>${passed}</span> &nbsp; <b>失败：</b><span style='color:red;'>${failed}</span>
</div>`;
const allTable = `<table border='1' cellpadding='4' cellspacing='0' style='border-collapse:collapse;'>
  <thead>
    <tr>
      <th>用例名称</th><th>开始时间</th><th>结果</th><th>耗时(ms)</th><th>错误信息</th>
    </tr>
  </thead>
  <tbody>${allRows}</tbody></table>`;

const htmlReport = `${summaryHtml}<div style='margin-top:8px;'><b>全部用例详情：</b></div>${allTable}`;

// Configure mail transporter for QQ SMTP
const transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
        user: 'your_qq@qq.com',      // your QQ email
        pass: 'your_app_password'    // QQ邮箱授权码
    }
});

// 优化邮件主题
const mailOptions = {
    from: 'your_qq@qq.com',
    to: 'recipient@example.com',
    subject: `Playwright测试报告 ${dateStr} | 总:${total} 通过:${passed} 失败:${failed}`,
    html: `<h2>测试报告</h2>${htmlReport}`
};

// Send email
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.error('Error sending email:', error);
    }
    console.log('Email sent:', info.response);
});